<template>
  <fieldset class="task__box">
    <legend class="task__box__legend">{{rankCN}}</legend>
    <div class="task__box--content">
      <div v-for="task in taskList" :key="task.id" class="task__box--list">
        {{task.name}} ：{{new Date(task.startDate).toLocaleDateString()}} 至 {{new Date(task.endDate).toLocaleDateString()}}
      <span @click="deletTask(task)" class="task__box--del">X</span>
      </div>
    </div>
  </fieldset>
</template>

<script>
import Task from '@/core/Task.js'
import db from '@/core/db.js'
import bus from '@/core/bus.js'

export default {
  name: 'TaskBox',
  data () {
    return {
      editTask: new Task('新任务'),
      taskList: []
    }
  },
  props: {
    rank: {
      type: String,
      default: 'rank-1'
    },
    date: {
      type: Date
    }
  },
  computed: {
    rankCN () {
      return this.rank === 'rank-1' ? '很重要-很紧急' : this.rank === 'rank-2' ? '重要-不紧急' : this.rank === 'rank-3' ? '不重要-紧急' : '不重要-不紧急'
    }
  },
  watch: {
    date () {
      this.getTasks()
    }
  },
  methods: {
    getTasks () {
      db.Task.where('rank').equalsIgnoreCase(this.rank).and(task => {
        return task.startDate <= this.date.getTime() && task.endDate >= this.date.getTime()
      }).toArray(tasks => {
        tasks.forEach(task => {
          task.init(true)
        })
        this.taskList = tasks
      })
    },
    deletTask (task) {
      task.delete().then(() => {
        bus.$emit('update')
      })
    }
  },
  mounted () {
    this.getTasks()
    bus.$on('update', () => {
      this.getTasks()
    })
  }
}
</script>

<style lang="stylus">
  .task__box
    .task__box__legend
      padding 0px 5px
    .task__box--del
      margin-left 10px
      cursor pointer
    .task__box--list
      border-bottom: 1px dashed #d9d9d9
      padding 10px 0px
      margin 0px 15px
    .task__box--content
      overflow-y auto
      height: calc(100% - 22px)
</style>
